package com.xh3140.android.widget.dialog.view;

import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.view.Gravity;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.LinearLayoutCompat;

import com.xh3140.android.widget.dialog.params.InputParams;
import com.xh3140.android.widget.dialog.utils.DrawableUtils;
import com.xh3140.android.widget.dialog.utils.LayoutParamsBuilder;
import com.xh3140.android.widget.dialog.utils.ViewUtils;

/**
 * 输入主体视图
 */
public class InputView extends AppCompatEditText {
    public InputView(@NonNull Context context) {
        this(context, new InputParams(context));
    }

    public InputView(@NonNull Context context, @NonNull InputParams params) {
        super(context);
        configView(params);
    }

    /**
     * 配置视图
     *
     * @param params 输入主体视图配置属性
     */
    public void configView(@NonNull InputParams params) {
        if (params.inputType != InputType.TYPE_NULL) {
            setInputType(params.inputType);
        }
        if (params.text != null) {
            setText(params.text);
            setSelection(0, params.text.length());
        }
        setTextSize(params.textSize);
        setTextColor(params.textColor);
        setTypeface(getTypeface(), params.typeface);
        setHint(params.hint);
        setHintTextColor(params.hintColor);
        setGravity(params.gravity);
        setSingleLine(params.isSingleLine);
        if (params.maxLines > 0) {
            setMaxLines(params.maxLines);
        }
        setMaxEms(params.maxEms);
        if (params.maxLength > 0) {
            setFilters(new InputFilter[]{new InputFilter.LengthFilter(params.maxLength)});
        }
        if (params.backgroundResource != 0) {
            setBackgroundResource(params.backgroundResource);
        } else {
            setBackground(DrawableUtils.gradient(params.backgroundColor, params.radius, params.strokeWidth, params.strokeColor));
        }
        ViewUtils.setPaddingRelative(this, params.padding);
        setLayoutParams(LayoutParamsBuilder.ofMW(LinearLayoutCompat.LayoutParams.class)
                .setWeight(1f)
                .setGravity(Gravity.CENTER_HORIZONTAL)
                .setMarginsRelative(params.margins)
                .build());
        ViewUtils.setTextViewHeight(this, params.height);
        setFocusable(true);
        setFocusableInTouchMode(true);
        requestFocus();
        if (params.callback != null) {
            params.callback.callback(this);
        }
    }

}
